package org.lgiavedoni.android.franq.service.message;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.lgiavedoni.android.franq.core.message.MessageInterceptor;
import org.lgiavedoni.android.franq.core.service.CoreService;
import org.lgiavedoni.android.franq.core.service.Service;
import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.util.string.StringUtil;

public class MessageInterceptorService extends Service implements CoreService {

	public static final MessageInterceptorService inst = new MessageInterceptorService();

	private static Set<MessageInterceptor> interceptors = new HashSet<MessageInterceptor>();

	private static final String IMPLEMENTATIONS_KEY = "interceptors";

	public MessageInterceptor getMessageInterceptor(String userText) {
		if (!isStarted())
			start();
		// TODO improve the search logic
		try {
			if (!StringUtils.isEmpty(userText))
				for (MessageInterceptor mi : interceptors) {
					if (StringUtil.containAnyOf(userText, mi.getInterceptorTags())) {
						return mi.getClass().newInstance();
					}
				}
			return null;
		} catch (Exception e) {
			Logger.inst.error(e);
			return null;
		}
	}

	@Override
	public String getServiceName() {
		return "messageInterceptor";
	}

	@Override
	protected void startInternal() {

	}

	@Override
	protected void stopInternal() {
		interceptors.clear();
	}

	@Override
	public void _run() {
		for (Object obj : getImplementations(IMPLEMENTATIONS_KEY)) {
			interceptors.add((MessageInterceptor) obj);
		}
	}
}
